<!-- <script> {{{ -->
<script setup lang="ts">
import {nextTick, ref, watch} from 'vue'
import {Server} from '@/stores/ajax';
import {Delta, QuillEditor} from '@vueup/vue-quill'
import {GetUserState} from '@/stores/userState';
import {QuillDeltaToHtmlConverter} from 'quill-delta-to-html';

import {timeFormat} from '@/utils'
import {ServerUtils} from '@/serverUtils';
import Intersect from '@/components/intersect.vue'
import {component as v} from "v-viewer"

let user = GetUserState()
// rollToPid 是一开始滚动到的页面
const props = defineProps({
    ppid: Number,
    maxWordsLength: Number,
    rollToPid: Number,
    showOnlyAuthor: Boolean,
    sortby: String,
    direction: String,
    page: Number,
    hideAvatar: Boolean,
    hideReplyAvatar: Boolean
})
let rollToPid = Number(props.rollToPid)
const posts = ref<any>({})
let loading = false
let posts_per_page = 10

let onlyAuthor = $ref(false)
let currentPage = ref(props.page ?? 1)
const refresh = async () => {
    posts.value.list = []
    console.log(props.sortby)
    nextTick(async () => {
        await ServerUtils.getSubPosts(Number(props.ppid), ['star'], currentPage.value, posts_per_page, onlyAuthor, null, props.sortby, props.direction).then(res => {
            if (res) {
                posts.value.list = res.subPosts.list
                posts.value.total = Number(res.subPosts.total)
            }
        })
    })
}
refresh().then(() => {
    if (props.rollToPid) {
        rollToPid = Number(props.rollToPid)
        ServerUtils.getSubPostsList(Number(props.ppid)).then(res => {
            console.log(res)
            const subPostsList = res.subPostsList.list as Number[]
            console.log(subPostsList, rollToPid)
            const page = subPostsList.indexOf(rollToPid) / posts_per_page + 1 >> 0
            // if page = 0, cannot find subpost
            if (page) {
                currentPage.value = page
                nextTick(() => {
                    const id = 'post:' + rollToPid
                    setTimeout(() => {
                        document.getElementById(id)?.scrollIntoView({block: 'center'});
                    }, 300)
                })
            } else {return }
        })
    }
})
defineExpose({refresh, currentPage})
let subCommentEditor = $ref<any>()
const handleClickSubComment = (post: any, toComment = post) => {
    // Dynamically move the editor below the post when 回复 is clicked.
    const editor: HTMLElement = subCommentEditor.editor
    const holder = document.getElementById(`editor-holder-${post.pid}`)
    if (!holder) return
    commentingPid.value = post.pid
    holder.appendChild(subCommentEditor.editor)
    editor.style.display = 'block'
    subCommentEditor.post = toComment
    subCommentEditor.getQuill().root.dataset.placeholder = `回复@${toComment.user.user_name}:`
    nextTick(() => {subCommentEditor.getQuill().focus()})
}
let maxPostWordsLength = $ref(150)
const getQuillHTML = (editor: any) => {
    return new QuillDeltaToHtmlConverter(editor.getContents().ops, {}).convert()
}

const handleSubCommentCommit = async (post: any) => {
    console.log(subCommentEditor.getText())
    if (!ServerUtils.checkQuillWordsNum(
        subCommentEditor, 5, maxPostWordsLength)) return
    console.log(subCommentEditor.post)
    let content = getQuillHTML(subCommentEditor)
    if (subCommentEditor.post.pid != post.pid) {
        content = `<span class="remark-label">回复</span>
        <span class="remark-reply-name">@${subCommentEditor.post.user.user_name}</span>:` + content
    } else {
        content = content
    }
    await Server.post('/post/comment', {
        pid: post.pid,
        content
    }, true).then(res => {
        if (res.data && res.data.code == 0) {
            subCommentEditor.setContents(new Delta())
        }
        nextTick(() => loadSubpost(post, 1, true))
    })
}
// https://blog.csdn.net/rain097790/article/details/51332268
const pagination = (pageNo: number, pageSize: number, array: Array<any>) => {
    let offset = (pageNo - 1) * pageSize;
    return (offset + pageSize >= array.length) ?
        array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
}
const handleExpandSubComments = (post: any) => {
    post.expandSubComment = true
}
const subpostPageSize = 5
const unExpandedPageSize = 2
const commentingPid = ref(0)


let onlyAuthorChange = (v: any) => {
    refresh()
}

const handleSubcommentChange = (val: number, post: any) => {
    loadSubpost(post, val)
}
const loadSubpost = async (post: any, page = 1, force = false) => {
    // console.log("enter loading", post.pid,post.subpost_num)
    if (post.subpost_num > 0 || force) {
        // console.log("loading", post.pid)
        nextTick(() => {
            ServerUtils.getSubPosts(Number(post.pid), ['collect', 'star'], page, subpostPageSize).then(res => {
                post.comments = res.subPosts.list
                post.subpost_num = Number(res.subPosts.total)
            })
        })
    }
}
watch(currentPage, v => nextTick(refresh))
</script>
<!-- }}} -->

<template>
    <div v-if='$DEV' class="dev-tag">CommentList1</div>
    <QuillEditor theme="bubble" content-type="delta"
        ref="subCommentEditor" style="display: none;" />

    <div class="comment-block"
        @click.stop="commentingPid = 0">
        <div class="fhs">
            <el-pagination hide-on-single-page
                v-model:current-page="currentPage"
                :page-size="posts_per_page" :small="true"
                layout="total, prev, pager, next ,jumper"
                :total="posts.total || 0"
                style="flex-grow: 1;" />
            <div style="flex-grow: 1;" />
            <div class="only-author hidebox"
                v-if='showOnlyAuthor && posts.total'>
                <el-checkbox v-model="onlyAuthor"
                    @change="onlyAuthorChange" label="只看作者"
                    size="large" />
            </div>
        </div>
        <div v-if='!posts.total' class="fh"
            style='padding: 0 20px;'>
            <el-divider>
                <div style='color: #ccc;'>
                    暂无评论
                </div>
            </el-divider>
        </div>
        <div class="post-list">
            <div class="post-item fhs"
                @click.stop="commentingPid = commentingPid == item.pid ? item.pid : 0"
                v-for="item in posts.list"
                :id='"post:" + item.pid'>
                <intersect @enter="loadSubpost(item)">
                </intersect>
                <div class="user-avatar">
                    <el-avatar :size="45"
                        :src="Server.fileBaseURL + item.user.avatar">
                    </el-avatar>
                </div>
                <div class="rightsize fvs">
                    <div class="user-name">
                        {{ item.user.user_name}}
                    </div>
                    <v class="viewer">
                        <div class="content"
                            v-dompurify-html="item.content" />
                    </v>
                    <div class="last-line fhs">
                        <div class="publish-time"
                            v-text="timeFormat(item.create_time)" />
                        <img src="icon-like.png"
                            @click="ServerUtils.star(item)"
                            class="icon-like hp">
                        <div class="like-num">
                            {{ item.star?.length ||
                                    ''
                            }}
                        </div>
                        <div class="remark hp"
                            @click="handleClickSubComment(item)">
                            回复</div>
                    </div>
                    <div class="remarks-area">
                        <div class="remark-item fhs"
                            v-if="item.comments"
                            v-for="subitem of pagination(1, item.expandSubComment ? subpostPageSize : unExpandedPageSize, item.comments)">
                            <div class="remark-user-avatar">
                                <el-avatar :size="30"
                                    :src="Server.fileBaseURL + subitem.user.avatar">
                                </el-avatar>
                            </div>
                            <div class="remark-rightside">
                                <span
                                    class="remark-username">
                                    {{
                                            subitem.user.user_name
                                    }}
                                </span>
                                <span class="remark-content"
                                    v-dompurify-html="subitem.content" />
                                <div class="last-line fhs">

                                    <div class="publish-time"
                                        v-text="timeFormat(subitem.create_time)" />

                                    <img src="icon-like.png"
                                        @click="ServerUtils.star(subitem)"
                                        class="icon-like hp">
                                    <div class="like-num">
                                        {{
                                                subitem.star_count
                                                || ''
                                        }}
                                    </div>
                                    <div class="remark hp"
                                        @click="handleClickSubComment(item, subitem)">
                                        回复</div>
                                </div>

                            </div>
                        </div>
                        <div v-if="item.comments && item.comments.length > unExpandedPageSize && !item.expandSubComment"
                            class="label-show-all-remark hp"
                            v-text="`展开全部${item.subpost_num}条评论`"
                            @click="handleExpandSubComments(item)" />
                        <el-pagination
                            :page-size="subpostPageSize"
                            v-if="item.comments && item.expandSubComment"
                            small hide-on-single-page
                            layout="total, prev, pager, next "
                            :total="item.subpost_num"
                            @current-change="(val: number) => {handleSubcommentChange(val, item)}"
                            style="" />
                    </div>
                    <div class="subcomment-area fhs"
                        :class="item.pid == commentingPid ? 'active' : ''">
                        <div class="reply-avatar"  v-if='!hideReplyAvatar'>
                            <el-avatar :size="45"
                                :src="Server.fileBaseURL + user.avatar" />
                        </div>
                        <div class="rightside fvs">
                            <!-- 输入框 -->
                            <div class="text-area"
                                :id="`editor-holder-${item.pid}`">

                            </div>

                            <el-button class="b-post"
                                @click="handleSubCommentCommit(item)"
                                type="primary">
                                发布
                            </el-button>
                        </div>
                    </div>
                    <div class="div-line"></div>
                </div>
            </div>
        </div>
        <el-pagination v-model:current-page="currentPage"
            hide-on-single-page :page-size="posts_per_page"
            :small="true"
            layout="total, prev, pager, next ,jumper"
            :total="posts.total || 0"
            style="flex-grow: 1;" />
    </div>
</template>

<style scoped lang="scss">
.comment-block {
    min-height: 30px;

    .post-list {
        .post-item {
            width: 100%;
            overflow: hidden;

            .user-avatar {
                margin: 0 16px 0px 10px;
            }

            .rightsize {
                flex-grow: 1;
            }

            .user-name {
                font-size: 16px;
                color: #333333;
                font-weight: bold;
                margin-bottom: 4px;
            }

            .content {
                color: #333333;
                font-size: 16px;
                line-height: 1.5;
                margin-bottom: 4px;
            }

            .last-line {
                align-items: center;
                font-size: 14px;
                line-height: 2;
                color: #999999;

                .publish-time {
                    margin-right: 10px;
                }

                .icon-like {
                    width: 16px;
                    height: 16px;
                    filter: opacity(0.4);
                    margin-right: 2px;
                }

                .like-num {
                    margin-right: 10px;

                }
            }

            .remarks-area {
                .remark-user-avatar {
                    margin-right: 8px;
                }

                .remark-rightside {

                    color: #333333;
                    font-size: 16px;
                    line-height: 1.5;
                    margin-bottom: 4px;
                }

                .remark-username {
                    font-size: 16px;
                    color: #333333;
                    font-weight: bold;
                }

                .label-show-all-remark {
                    font-size: 14px;
                    color: #999999;
                }
            }

            .remark-username::after {
                content: "";
                display: inline-block;
                margin-right: 4px;
            }

            .div-line {

                width: 70%;
                border-top: 1px solid #0003;
            }
        }
    }

    .subcomment-area {
        /* transition: transform .3s ease-in-out, opacity .3s ease-in-out; */
        transition: max-height .50s ease-in-out;
        overflow: hidden;
        max-height: 0px;

        &.active {
            max-height: 100px;
        }

        .reply-avatar {
            margin: 10px 20px 0 10px;
        }

        .rightside {
            flex-grow: 1;
        }

        .text-area {
            margin-right: 20px;
            height: 80px;
            border: 1px solid #eee;
            border-radius: 8px;
        }

        .b-post {
            margin: 8px 0 30px;
            font-size: 16px;
            max-width: 100px;
            letter-spacing: 10px;
        }

        .b-post.b-post {
            text-indent: -10px;
            direction: rtl;
        }
    }

}

@keyframes FadeIn {
    0% {
        height: 10px;
    }

    100% {
        height: 50px;
    }
}

@keyframes FadeOut {
    0% {
        opacity: 1;
        height: initial;
    }

    99% {
        opacity: 0;
        height: initial;
    }

    100% {
        height: 0;
        opacity: 0;
        height: 0;
    }
}
</style>
<style lang="scss">
.remark-content p:first-of-type {
    display: inline;
    margin-left: 10px;
}

.comment-block img {
    max-width: 100% !important;
}
</style>
